package com.huluobo.a2202mvvm_im_douyindemo.adapter;

import android.graphics.Color;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.huluobo.a2202mvvm_im_douyindemo.R;
import com.huluobo.a2202mvvm_im_douyindemo.live.MessageEntity;

import java.util.List;

/**
 * Created by LC on 2024/5/13.
 */
public class ChatRoomMessageAdapter extends BaseQuickAdapter<MessageEntity, BaseViewHolder> {
    private int[] resIds = {
            R.drawable.chat_bg_0,
            R.drawable.chat_bg_1,
            R.drawable.chat_bg_2,
            R.drawable.chat_bg_3,
            R.drawable.chat_bg_4,
            R.drawable.chat_bg_0,
            R.drawable.chat_bg_1,
            R.drawable.chat_bg_2,
            R.drawable.chat_bg_3,
            R.drawable.chat_bg_4,
            R.drawable.chat_bg_0,
            R.drawable.chat_bg_1,
            R.drawable.chat_bg_2,
            R.drawable.chat_bg_3,
            R.drawable.chat_bg_4
    };

    public ChatRoomMessageAdapter(@Nullable List<MessageEntity> data) {
        super(R.layout.item_chat_room_smg_layout, data);
    }

    @Override
    protected void convert(@NonNull BaseViewHolder baseViewHolder, MessageEntity messageEntity) {
        //设置聊天背景
        int index = (int) (resIds.length % (Math.random() * 10));
        baseViewHolder.setBackgroundResource(R.id.item_chat_room_ll, resIds[index]);

//        <span color = "red">123</span >
        // 张三:12312312
        String msg = messageEntity.getUsername() + ":" + messageEntity.getContent();

        //构建富文本编辑器
        SpannableStringBuilder builder = new SpannableStringBuilder(msg);

        //定义几个span的颜色
        ForegroundColorSpan blue = new ForegroundColorSpan(Color.BLUE);
        ForegroundColorSpan yellow = new ForegroundColorSpan(Color.YELLOW);
        ForegroundColorSpan red = new ForegroundColorSpan(Color.RED);

        //SPAN_INCLUSIVE_INCLUSIVE 前后是否包含元素
        //标记发送信息的名字为蓝色
        if (messageEntity.getUsername().equals("系统")) {
            builder.setSpan(red, 0, messageEntity.getUsername().length() + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        } else {
            builder.setSpan(blue, 0, messageEntity.getUsername().length() + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        }
        builder.setSpan(yellow, messageEntity.getUsername().length() + 1, msg.length(),
                Spanned.SPAN_INCLUSIVE_INCLUSIVE);

        baseViewHolder.setText(R.id.item_chat_room_content_tv, builder);
    }
}
